<?php

namespace app\job;

use app\model\Config;
use app\model\GoodsOrders;
use app\model\SuperOrders;
use app\tool\Random;
use Exception;
use GuzzleHttp\Client;
use think\db\exception\ModelNotFoundException;
use think\queue\Job;

class Task
{
	

	public function fire(Job $job, $data)
	{
		
		$rt = $this->doJob($data);
		if ($rt) {
			$job->delete();
			return true;
		}
		
		// 重试三次失败
			if ($job->attempts() >= 3) {
				$job->release(60*60*24);
				return false;
			}
		
		//执行失败10S后重试
		$job->release(10);
		
	}
	
	public function doJob($data)
	{
		try {
			if (array_key_exists('action', $data)) {
				echo $data['action'];
				//超时系统自动操作
				switch ($data['action']) {
                    case 'goods_order_confirm':
                        //订单自动确认
                        $order_id = $data['order_id'];
                        $row = GoodsOrders::findOrFail($order_id);
                        if ($row->status == 3) {
                            $row->status = 4;
                            $row->confirmtime = time();
                            $row->save();
                        }
                        break;
					case 'goods_order_timeout':
						//订单超时取消
						$order_id = $data['order_id'];
						$row = GoodsOrders::findOrFail($order_id);
						if ($row->status == 1) {
							//取消
							$row->status = 6;
							$row->save();
						}
						break;
					case 'super_order_timeout':
						//订单超时取消
						$order_id = $data['order_id'];
						$row = SuperOrders::findOrFail($order_id);
						if ($row->status == 1) {
							//取消
							$row->status = 6;
							$row->save();
						}
						break;
					case 'train_order_expire':
						//过期处理
						$order_id = $data['order_id'];
						$row = TrainOrders::findOrFail($order_id);
						if ($row->status == 2) {
							//使用中->已过期
							$row->status = 3;
							$row->save();
						}
						break;
					case 'train_make_pdf':
						$order_id = $data['order_id'];
						$row = TrainOrders::findOrFail($order_id);
						$class = TrainSchoolLevelVipTrainerClass::whereIn('id',$row->class_ids)->select();
						
						$official_seal = Config::getFieldByName('official_seal', 'value');
						$contract = Config::getFieldByName('contract', 'value');
						//L 横排   P竖排
						//Unit：设置页面的单位。pt：点为单位，mm：毫米为单位，cm：厘米为单位，in：英尺为单位
						//Format：设置打印格式，一般设置为A4
						//Unicode：为true，输入的文本为Unicode字符文本
						//Encoding：设置编码格式，默认为utf-8
						//Diskcache：为true，通过使用文件系统的临时缓存数据减少RAM的内存使用
						//实例化
						$pdf = new TCPDF('P', 'pt', 'A4', true, 'utf-8', true, false);
						//设置文件信息
						$pdf->SetCreator(PDF_CREATOR);
						$pdf->SetFont('stsongstdlight', '', 14);
						$pdf->SetAuthor(PDF_CREATOR);
						$pdf->SetTitle("pdf test");
						$pdf->SetSubject('TCPDF Tutorial');
						$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
						// 页眉距离顶部的距离
						$pdf->SetHeaderMargin(5);
						//删除预定义的打印 页眉/页尾
						$pdf->setPrintHeader(false);
						$pdf->setPrintFooter(false);
						//设置默认等宽字体
						$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
						/*设置页面边幅：Left：左边幅Top：顶部边幅Right：右边幅Keepmargins：为true时，覆盖默认的PDF边幅。 */
						// $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP,PDF_MARGIN_RIGHT);
						/*设置单元格的边距：Left：左边距Top：顶部边距Right：右边距Bottom：底部边距。*/
						// 设置左、上、右的间距
						$pdf->SetMargins('15', '10', '15');
						$pdf->setCellPaddings(10, 0, 0, 0);
						//添加一个页面
						$pdf->AddPage();
						$time = date('Y-m-d');
						//如果要对html指定 宽度  writeHTMLCell更方便
						// $pdf->writeHTMLCell(0, 0, 0, '', $html, 0, 1, 0, true, '', true);
						$pdf->writeHTML($contract);
						
						$train = "项目：{$row->train->name}<br>校区：{$row->school->name}<br>级别：{$row->level->name}<br>会员：{$row->vip->name}<br>教练：{$row->trainer->name}<br>金额：{$row->pay_amount}元<br>";
						foreach ($class as $value){
							$train.= "班级：{$value->name} 上课时间：{$value->weekdata_text} {$value->starttime} {$value->endtime}<br>";
						}
						$pdf->MultiCell(500, 20, $train, 0, 'L', false, 1, 20, 700, true, 0, true);
						$text1 = '甲方（盖章）:<br/>签约时间：' . $time;
						$text2 = '乙方（签字）:<br/>签约时间：' . $time;
						// a4转成px是794px*1123px
						$pdf->MultiCell(200, 20, $text1, 0, 'L', false, 1, 20, 700, true, 0, true);
						$pdf->MultiCell(300, 20, $text2, 0, 'L', false, 1, 300, 700, true, 0, true);
						$pdf->image(config('app.static_host') . $official_seal, 120, 670, 80);
						$pdf->image(config('app.static_host') . $row->sign, 400, 670, 80);
						$rand = Random::ordersn();
						$client = new Client();
						$upload = $client->post(config('app.static_host').'/api/common/upload', [
							'multipart' => [
								[
									'name' => 'file',
									'contents' => $pdf->getPDFData(),
									'filename' =>"$rand.pdf"
								],
							]
						]);
						$upload = json_decode($upload->getBody()->getContents());
						if ($upload->code!=1){
							 throw new Exception('合同上传失败');
						}
						$row->contract = $upload->data->url;
						$row->save();
						break;
				}
			}
		} catch (ModelNotFoundException $e) {
			dump('找不到数据');
			return true;
		} catch (Exception $e) {
			dump($e->getMessage());
			dump($e->getLine());
			return false;
		}
		return true;
	}
	
	
}
